<template>
  <tl-sub-page :append-to-body="true" :render="render" :visible.sync="visible" v-dialogDrag :title="title" :close-on-click-modal="false" class="tl-dialog" width="1000px" @open="open" @close="close">
    <div class="project-container">
      <div class="project-main" :style="{ height: mainHeight + 'px' }">
        <el-scrollbar class="customer-main-container">
          <div style="padding:0 10px; margin-right: 5px;">
            <el-form class="tl-form" ref="form" :model="model" :rules="rules" label-width="150px" :disabled="disableEditSubmit">
              <el-row>
                <el-col :span="24">
                  <el-form-item label="所属里程碑及任务" prop="milepostname" :rules="rules.validateRequire">
                    <el-input v-model="model.milepostname" disabled class="tl-ref-selector">
                      <el-button slot="append" type="primary" icon="el-icon-search" @click="openMpmProjectMilepostDialog" v-if="!disableBytaskstate"></el-button>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <!-- <el-row>
                <el-col :span="12">
                  <el-form-item label="任务类型" prop="tasktype" :rules="rules.validateRequire">
                    <el-select v-model="model.tasktype" filterable clearable>
                      <el-option v-for="item in codeModel.tasktypeList" :key="item.code" :label="item.name"
                        :value="item.code" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="优先级" prop="taskpriority" :rules="rules.validateRequire">
                    <el-select v-model="model.taskpriority" filterable clearable>
                      <el-option v-for="item in codeModel.taskpriorityList" :key="item.code" :label="item.name"
                        :value="item.code" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row> -->
              <el-row>
                <el-col :span="12">
                  <el-row :gutter="8">
                    <el-col :span="20">
                      <el-form-item label="任务名称" prop="taskname" :rules="rules.validateRequire">
                        <el-input v-model="model.taskname" :disabled="disableBytaskstate"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="4" v-show="model.taskexplain">
                      <el-tooltip :content="model.taskexplain" placement="top" style="font-size:20px; margin-top:4px">
                        <i class="el-icon-info" style="color: #909399"/>
                      </el-tooltip>
                    </el-col>
                  </el-row>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="排序码">
                    <el-input-number v-model="model.sortcode" controls-position="right" :step="1" :min="0" style="width:100%"></el-input-number>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="任务内容" prop="taskdetail" :rules="rules.validateRequire">
                    <el-input v-model="model.taskdetail" type="textarea" :rows="4" maxlength="1000" show-word-limit :disabled="disableBytaskstate"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="责任人" prop="responsible" :rules="rules.validateRequire">
                    <tl-ref-stakeholder v-model="model.responsible" :initDisplayData.sync="model.responsible" fieldKey="usercode" @confirm="getmpmProjectStakeData" :externalSelectedRowKeys="model.responsiblecode" title="选择任务责任人" :externalQueryParam="externalQueryParamForStakeholder" :isSingleSelect="true" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="责任人工号" prop="responsiblecode" :rules="rules.validateRequire">
                    <el-input v-model="model.responsiblecode" disabled></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="计划开始日期" prop="planstartdate" :rules="rules.validateRequire">
                    <el-date-picker v-model="model.planstartdate" type="date" @change="changeTaskPlanStartDate" :disabled="disableBytaskstate" placeholder="例：2021-01-01" value-format="yyyy-MM-dd"> </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="计划完成日期" prop="planenddate" :rules="rules.validateRequire">
                    <el-date-picker v-model="model.planenddate" type="date" @change="changeTaskPlanEndDate" placeholder="例：2021-01-01" value-format="yyyy-MM-dd"> </el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
              <!-- <el-row>
                <el-col :span="12">
                  <el-form-item label="任务进度" prop="taskschedule">
                    <el-input-number v-model="model.taskschedule" :disabled="true" style="width:95%" controls-position="right">
                    </el-input-number><span>%</span>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="任务状态" prop="taskstate">
                    <el-select v-model="model.taskstate" filterable clearable :disabled="true">
                      <el-option v-for="item in codeModel.taskstateList" :key="item.code" :label="item.name"
                        :value="item.code" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row> -->
            </el-form>
            <tl-feedback-line ref="feedbackRef" style="margin-top: 10px" @resize="resizeHandler"></tl-feedback-line>
            <tl-approval-history ref="history" sourceType="MpmProjectTask" :sourceId="model.id" />
            <div slot="footer" class="dialog-footer" style="float: right; margin-right:10px;">
              <el-button :type="disableEditSubmit === false ? 'text' : 'primary'" @click="doCancelEdit">取消</el-button>
              <el-button type="primary" @click="doSubmitEdit" :loading="saveLoading" v-show="!disableEditSubmit"> <svg-icon icon-class="save" />保存 </el-button>
              <el-button type="primary" @click="distributeTask" :loading="submitLoading" v-show="showDistrbuteButton"> <svg-icon icon-class="send" />下发任务 </el-button>
              <tl-attachment-task sourceType="MpmProjectTaskFeedback" :sourceId="model.id" btnTitle="反馈附件" :editable="false"></tl-attachment-task>
            </div>
            <tlmpmProject-milepost-ref ref="mpmProjectMilepostRef" title="里程碑及任务选择" @confirm="getMpmProjectMilepostData" :viewAllMilePost="true" :isSingleSelect="true" :externalQueryParam="externalQueryParamForPool"></tlmpmProject-milepost-ref>
          </div>
        </el-scrollbar>
      </div>
    </div>
  </tl-sub-page>
</template>

<script>
/** mixins */
import { mixin_approval_edit } from '@tapui/mixins/mixin_approval_edit'
/** 子组件 */
import tlmpmProjectMilepostRef from '@/views/mpm/mpmProjectMilepost/refList'
import tlRefStakeholder from '../mpmProjectStakeholder/refList'
import tlFeedbackLine from '../mpmProjectTaskFeedback/feedbackLine'
import tlAttachmentTask from '../../../components/myAttachment/myAttachmentTask'

/** 工具类 */
import { putAction, getAction, postAction, deleteAction } from '@tapui/utils/http'
import { MPM_TASK_STATE } from '@/const/const'
/** VUE配置 */
export default {
  mixins: [mixin_approval_edit],
  components: { tlmpmProjectMilepostRef, tlRefStakeholder, tlFeedbackLine, MPM_TASK_STATE, tlAttachmentTask },
  data() {
    return {
      moduleTitle: '项目任务',
      urlPrefix: '/mpm/projectTask/',
      url: {
        // 额外的url
        // loadPlanInfo: '/mpm/projectPlan/loadPlanInfo',
        updateResponsible: 'mpm/projectTask/updateResponsible',
        distributeTask: '/mpm/projectTask/distributeTask',
        milepostlist: '/mpm/projectMilepost/list',
        updateAbnormalState: '/mpm/project/updateAbnormalState'
      },
      externalQueryParamForPool: {},
      // 人员组件查询参数
      externalQueryParamForStakeholder: {
        qry_projectcode: '' // 项目编号
      },
      oldresponsiblecode: undefined,
      milepostPlanFinishTime: undefined,
      oldplanenddate: undefined,
      mainHeight: 300,
      attachmenteditable: false
    }
  },
  props: {
    projectinfo: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  computed: {
    // 表单组件禁用
    disableBytaskstate() {
      if (this.model.taskstate === MPM_TASK_STATE.notStart) {
        return false
      }
      return true
    },
    // 下发按钮的显示/隐藏
    showDistrbuteButton() {
      // 下发前编辑状态时显示
      if (!this.stateApproval && !this.stateAdd) {
        return true
      }
      return false
    }
  },
  created() {
    this.mainHeight = 300
  },
  methods: {
    // 高度函数
    resizeHandler() {
      this.mainHeight = document.body.getBoundingClientRect().height - 180
    },
    // 实时更新项目状态
    updateAbnormalState() {
      putAction(this.url.updateAbnormalState, { projectcode: this.model.projectcode })
        .then((res) => {
          if (res.success) {
            // 若更新了项目状态则提示
            if (res.result.changeState) {
              this.$tap.message(res.result.message, 'success')
              // 套娃回调更新项目状态
              this.$emit('refresh', true)
            }
          } else {
            this.$tap.alert(res.message, 'warning')
          }
        })
        .catch((err) => {
          this.$tap.alert(err.message, 'warning')
        })
    },
    /** 提交后执行 */
    async afterSubmit() {
      let newplanenddate = new Date(this.model.planenddate).getTime()
      let currentdate = new Date()
      currentdate.setHours(0, 0, 0, 0)
      currentdate = currentdate.getTime()
      // 若修改了计划完成日期，旧计划完成日期小于当前日期，且新计划完成日期大于当前日期则执行实时更新项目状态方法
      if (this.oldplanenddate !== newplanenddate) {
        if (this.oldplanenddate < currentdate) {
          await this.updateAbnormalState()
        }
        this.oldplanenddate = new Date(this.model.planenddate).getTime()
      }
    },
    // 查询里程碑及任务信息
    queryMilepost(milepostcode) {
      let param = {
        qry_operatecode: milepostcode,
        qry_enabled: 1
      }
      getAction(this.url.milepostlist, param).then((res) => {
        if (res.success) {
          this.milepostPlanFinishTime = res.result.dataList[0].planfinishtime
        } else {
          this.$tap.alert(res.message, 'warning')
        }
      })
    },
    // 计划完成日期监听
    changeTaskPlanEndDate() {
      if (!this.model.planenddate) {
        return
      }
      if (!this.model.planstartdate) {
        this.$tap.alert('请先填写任务的计划开始日期！', 'warning')
        this.$set(this.model, 'planenddate', null)
        return
      }
      // 若计划开始日期大于计划完成日期则提示
      if (new Date(this.model.planenddate).getTime() < new Date(this.model.planstartdate).getTime()) {
        this.$tap.alert('任务的计划开始日期不能大于计划完成日期！', 'warning')
        this.$set(this.model, 'planenddate', null)
        return
      }
      // 若任务计划完成日期大于里程碑及任务日期则提示
      if (new Date(this.model.planenddate).getTime() > new Date(this.milepostPlanFinishTime).getTime()) {
        this.$tap.alert('任务的计划完成日期不能大于所属里程碑及任务的计划达成日期！', 'warning')
        this.$set(this.model, 'planenddate', null)
        return
      }
    },
    // 计划开始日期监听
    changeTaskPlanStartDate() {
      if (!this.model.planstartdate) {
        return
      }
      // 没选里程碑及任务就没有里程碑及任务达成日期，无法校验
      if (!this.milepostPlanFinishTime) {
        this.$tap.alert('请先选择任务所属里程碑及任务！', 'warning')
        this.$set(this.model, 'planstartdate', null)
        return
      }
      // 若任务计划开始日期大于里程碑及任务日期则提示
      if (new Date(this.model.planstartdate).getTime() > new Date(this.milepostPlanFinishTime).getTime()) {
        this.$tap.alert('任务的计划开始日期不能大于所属里程碑及任务的计划达成日期!', 'warning')
        this.$set(this.model, 'planstartdate', null)
        return
      }
    },
    // 任务下发不走审批，修改责任人后也能重新下发（给新责任人发送消息提醒）
    distributeTask() {
      this.saveLoading = true
      this.submitLoading = true
      putAction(this.url.distributeTask, { id: this.model.id })
        .then((res) => {
          if (res.success) {
            this.$tap.message(res.message, 'success')
          } else {
            this.$tap.alert(res.message, 'warning')
          }
          this.saveLoading = false
          this.submitLoading = false
          this.$emit('refresh')
          this.visible = false
        })
        .catch((err) => {
          this.saveLoading = false
          this.submitLoading = false
        })
    },
    assignDefaultValue() {
      if (this.isAdd) {
        this.$set(this.model, 'applyorgcode', this.org.code)
        this.$set(this.model, 'applyorgname', this.org.name)
        this.$set(this.model, 'applydeptcode', this.dept.code)
        this.$set(this.model, 'applydeptname', this.dept.fullname)
        this.$set(this.model, 'applyusercode', this.user.code)
        this.$set(this.model, 'applyusername', this.user.name)
        this.$set(this.model, 'usercode', this.user.code)
        this.$set(this.model, 'username', this.user.name)
        this.$set(this.model, 'deptcode', this.dept.code)
        this.$set(this.model, 'orgcode', this.org.code)
        this.$set(this.model, 'taskschedule', '0')
        this.$set(this.model, 'taskstate', '0')
        this.$set(this.model, 'projectcode', this.projectinfo.projectcode)
        this.$set(this.model, 'projectname', this.projectinfo.projectname)
      }
    },
    // 人员选择后赋值
    addConfirm(rows, keys, values) {
      this.$set(this.model, 'responsiblecode', keys)
      this.$set(this.model, 'responsible', values)
    },
    /** 执行编辑提交 */
    doEdit() {
      this.saveLoading = true
      putAction(this.url.edit, this.model)
        .then((res) => {
          if (res.success) {
            this.$tap.message(res.message, 'success')
            this.queryData(this.model.id)
            this.isAdd = false
            // 下发后变更责任人时记录新责任人，用作判断
            if (this.model.state === 9) {
              let newresponsiblecode = this.model.responsiblecode
              // 若责任人已变更则执行下发
              if (newresponsiblecode !== this.oldresponsiblecode) {
                putAction(this.url.distributeTask, { id: this.model.id })
                  .then((res) => {
                    if (res.success) {
                      this.$tap.message(res.message, 'success')
                      this.oldresponsiblecode = newresponsiblecode
                    } else {
                      this.$tap.alert(res.message, 'warning')
                    }
                  })
                  .catch((err) => {
                    this.$tap.alert(err.message, 'warning')
                  })
              }
            }
          } else {
            this.$tap.alert(res.message, 'warning')
          }
          this.afterSubmit()
          this.saveLoading = false
          this.visible = false
        })
        .catch((err) => {
          this.saveLoading = false
        })
    },
    /** 执行编辑提交 */
    updateResponsible() {
      this.saveLoading = true
      let param = {
        id: this.model.id,
        responsiblecode: this.model.responsiblecode,
        responsible: this.model.responsible
      }
      putAction(this.url.updateResponsible, param)
        .then((res) => {
          if (res.success) {
            this.$tap.message(res.message, 'success')
            this.queryData(this.model.id)
            this.isAdd = false
          } else {
            this.$tap.alert(res.message, 'warning')
          }
          this.afterSubmit()
          this.saveLoading = false
        })
        .catch((err) => {
          this.saveLoading = false
        })
    },
    loaded() {
      // 页面加载完毕执行
      this.mainHeight = 300
      this.$refs.feedbackRef.queryTaskFeedbackList(this.model.id)
      this.externalQueryParamForStakeholder.qry_projectcode = this.projectinfo.projectcode
      this.oldresponsiblecode = undefined
      this.milepostPlanFinishTime = undefined
      this.oldplanenddate = new Date(this.model.planenddate).getTime()
      // 编辑状态下才需要查询里程碑及任务
      if (this.model.milepostcode && !this.disableEditSubmit) {
        this.queryMilepost(this.model.milepostcode)
      }
      // 记录任务责任人，用于权限判断
      if (this.model.responsiblecode) {
        this.oldresponsiblecode = this.model.responsiblecode
      }
    },
    /** 打开里程碑及任务参照 */
    openMpmProjectMilepostDialog() {
      const { projectcode } = this.model
      this.externalQueryParamForPool = {
        qry_projectcode: projectcode,
        qry_enabled: 1
        //  qry_milepoststate: 0
      }
      this.$refs.mpmProjectMilepostRef.visible = true
    },
    /** 获取里程碑及任务参照数据 */
    getMpmProjectMilepostData(selectionRow, selectKey, selectionValue) {
      this.$set(this.model, 'milepostname', selectionRow.milepostname)
      this.$set(this.model, 'milepostcode', selectionRow.operatecode)
      // 查询里程碑及任务计划达成日期
      this.queryMilepost(this.model.milepostcode)
    },
    getmpmProjectStakeData(selectionRow, selectKey, selectionValue) {
      this.$set(this.model, 'responsiblecode', selectionRow.usercode)
      this.$set(this.model, 'responsible', selectionRow.username)
    }
  }
}
</script>
